package util

import (
	"encoding/json"
	"fmt"
	"log"
	"regexp"
	"strconv"
	"strings"
)

type JsonStruct struct {
	Data map[string]interface{}
}
type ConfigStruct struct {
	Data string
}

func (c *ConfigStruct) Get(str string) interface{} {
	se := strings.Split(str, ".")
	var s1 string
	var s2 string
	data := strings.Split(c.Data, "[")
	for _, v := range data {
		if strings.Contains(v, se[0]) {
			s1 = v
			break
		}
	}
	if s1 == "" {
		log.Fatalln(fmt.Sprintf(`This field does not exist: %s`, se[0]))
		return nil
	}
	re := regexp.MustCompile(`(.*?)]`)
	res := re.FindStringSubmatch(s1)
	if res[1] != se[0] {
		log.Fatalln(fmt.Sprintf(`This field does not exist: %s`, res[1]))
		return nil
	}
	line := strings.Split(s1, "\n")
	for _, v := range line {
		if strings.Contains(v, se[1]) {
			s2 = v
			if strings.Contains(s2, "#") {
				continue
			}
			break
		}
	}
	if s2 == "" {
		log.Fatalln(fmt.Sprintf(`This field does not exist: %s`, se[1]))
		return nil
	}
	var newS2 string
	if strings.Contains(s2, " ") {
		newS2 = strings.Join(strings.Fields(s2), "")
	}
	var results interface{}
	if newS2 != "" {
		re = regexp.MustCompile(`(.*?)=`)
		res = re.FindStringSubmatch(newS2)
		if res[1] != se[1] {
			log.Fatalln(fmt.Sprintf(`This field does not exist: %s`, res[1]))
			return nil
		}
		field := strings.Split(newS2, "=")
		results = strings.TrimRight(field[1], "\r")
		return results
	}
	re = regexp.MustCompile(`(.*?)=`)
	res = re.FindStringSubmatch(s2)
	if res[1] != se[1] {
		log.Fatalln(fmt.Sprintf(`This field does not exist: %s`, res[1]))
		return nil
	}
	field := strings.Split(s2, "=")
	results = strings.TrimRight(field[1], "\r")
	return results
}
func (j *JsonStruct) GetString(str string) string {
	defer func() {
		if err := recover(); err != nil {
			log.Fatalln("Field error:field does not exist")
		}
	}()
	m := j.Data
	g := strings.Split(str, ".")
	var result interface{}
	for _, v := range g {
		if result == nil {
			result = m[v].(interface{})
			continue
		} else if _, err := strconv.Atoi(v); err == nil {
			index, err := strconv.Atoi(v)
			if err != nil {
				log.Fatalln(err)
				return ""
			}
			result = result.([]interface{})[index]
			continue
		} else {
			result = result.(map[string]interface{})[v]
			continue
		}
	}
	return result.(string)
}

func (j *JsonStruct) Unmarshal(jsonStr string) /*(*map[string]interface{})*/ error {
	m := make(map[string]interface{})
	data := []byte(jsonStr)
	if err := json.Unmarshal(data, &m); err != nil {
		log.Println("解析json出现异常：", err)
		return err
	}
	j.Data = m
	return nil
	//return &m, nil
}
func (j *JsonStruct) GetObject(key string) interface{} {
	obj := j.Data[key]
	return obj
}
